package com.jsmtr.rms.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ValidCodeController {

    private static final HttpHeaders HTTP_HEADERS;
    private static final Random RANDOM;

    static {
        HTTP_HEADERS = new HttpHeaders();
        HTTP_HEADERS.set("Pragma", "No-cache");
        HTTP_HEADERS.set("Cache-Control", "No-cache");
        HTTP_HEADERS.setDate("Expires", 0);
        HTTP_HEADERS.setContentType(MediaType.IMAGE_JPEG);
        RANDOM = new Random();
    }

    @RequestMapping(value = "/resources/captcha.jpeg")
    public ResponseEntity<byte[]> captcha(HttpSession session)
            throws IOException {

        int width = 73;
        int height = 18;

        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(getRandColor(200, 250));
        g.fillRect(1, 1, width - 1, height - 1);
        g.setColor(new Color(102, 102, 102));
        g.drawRect(0, 0, width - 1, height - 1);
        g.setFont(new Font("Times New Roman", Font.PLAIN, 20));
        g.setColor(getRandColor(160, 200));

        // 生成随机数,并将随机数字转换为字母
        String captchaStr = "";
        for (int i = 0; i < 4; i++) {
            int itmp = RANDOM.nextInt(26) + 65;
            char ctmp = (char) itmp;
            captchaStr += String.valueOf(ctmp);
            g.setColor(new Color(20 + RANDOM.nextInt(110), 20 + RANDOM
                    .nextInt(110), 20 + RANDOM.nextInt(110)));
            g.drawString(String.valueOf(ctmp), 15 * i + 10, 16);
        }
        g.dispose();

        //保存验证码到Session中
        session.setAttribute("validcode", captchaStr.toLowerCase());

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(image, "JPEG", out);

        try {
            return new ResponseEntity<byte[]>(out.toByteArray(), HTTP_HEADERS,
                    HttpStatus.OK);
        } finally {
            out.close();
        }
    }

    private Color getRandColor(int fc, int bc) {
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + RANDOM.nextInt(bc - fc);
        int g = fc + RANDOM.nextInt(bc - fc);
        int b = fc + RANDOM.nextInt(bc - fc);
        return new Color(r, g, b);
    }
}